package com.example.javaeekeshe.service.impl;

import com.example.javaeekeshe.service.IMailService;
import com.example.javaeekeshe.service.IRedisService;
import com.example.javaeekeshe.utils.messageUtils.IRandomMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailServiceImpl implements IMailService {

    @Autowired
    private JavaMailSenderImpl sender;
    @Autowired
    private IRandomMessageUtils messageUtils;
    @Autowired
    IRedisService redisService;

    @Override
    public boolean sendMail(String account,String body) {
        try {
            //复杂邮件
            MimeMessage mimeMessage = sender.createMimeMessage();
            //邮件发送助手
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            //发送方
            helper.setFrom("葛帅批官方<gjh2898534520@163.com>");
            //标题
            helper.setSubject("验证码" );
            //正文
            helper.setText(body, true);
            //接受方
            helper.setTo(account);
            sender.send(mimeMessage);
            System.out.println("邮件发送完毕");
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean sendRandomMail(String account) {
        String randomMessage = messageUtils.getRandomMessage();
        boolean b = sendMail(account, randomMessage);
        b=b&&redisService.setValue("yzm"+account,randomMessage);
        return b;
    }

}
